<template>
  <el-dialog
    :model-value="visible"
    title="编辑账单"
    width="500px"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item label="主叫手机号" prop="callerPhone">
        <el-select 
          v-model="form.callerPhone" 
          placeholder="请选择主叫手机号" 
          style="width: 100%"
          filterable
          @change="handleCallerPhoneChange"
        >
          <el-option
            v-for="phone in uniqueCallerPhones"
            :key="phone"
            :label="phone"
            :value="phone"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item label="被叫手机号" prop="calleePhone">
        <el-select 
          v-model="form.calleePhone" 
          placeholder="请选择被叫手机号" 
          style="width: 100%"
          filterable
        >
          <el-option
            v-for="phone in calleePhoneNumbers"
            :key="phone.phone"
            :label="getPhoneLabel(phone)"
            :value="phone.phone"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item label="虚拟号" prop="virtualNumber">
        <el-select 
          v-model="form.virtualNumber" 
          placeholder="请选择虚拟号" 
          style="width: 100%"
          filterable
        >
          <el-option
            v-for="virtual in filteredVirtualNumbers"
            :key="virtual.virtualNumber"
            :label="virtual.virtualNumber"
            :value="virtual.virtualNumber"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item label="通话时长(秒)" prop="callDuration">
        <el-input-number 
          v-model="form.callDuration" 
          placeholder="请输入通话时长"
          :min="0"
          controls-position="right"
          style="width: 100%"
        />
      </el-form-item>
      
      <el-form-item label="总费用(元)" prop="totalFee">
        <el-input-number 
          v-model="form.totalFee" 
          placeholder="请输入总费用"
          :min="0"
          :precision="2"
          :step="0.01"
          controls-position="right"
          style="width: 100%"
        />
      </el-form-item>
      
      <el-form-item label="服务费(元)" prop="virtualFee">
        <el-input-number 
          v-model="form.virtualFee" 
          placeholder="请输入服务费"
          :min="0"
          :precision="2"
          :step="0.01"
          controls-position="right"
          style="width: 100%"
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          确认修改
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { updateBillInfo, getBillInfoById } from '@/apis/billInfo'
import { getVirtualNumberInfo } from '@/apis/virtualNumber'
import { getPhoneNumberInfo } from '@/apis/phoneNumber'

export default {
  name: 'EditBill',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    billId: {
      type: [String, Number],
      default: null
    }
  },
  emits: ['update:visible', 'success'],
  setup(props, { emit }) {
    const formRef = ref()
    const submitLoading = ref(false)
    const allVirtualNumbers = ref([])
    const calleePhoneNumbers = ref([])
    
    const form = reactive({
      id: '',
      callerPhone: '',
      calleePhone: '',
      virtualNumber: '',
      callDuration: 0,
      totalFee: 0,
      virtualFee: 0
    })
    
    const rules = {
      callerPhone: [
        { required: true, message: '请选择主叫手机号', trigger: 'change' }
      ],
      calleePhone: [
        { required: true, message: '请选择被叫手机号', trigger: 'change' }
      ],
      virtualNumber: [
        { required: true, message: '请选择虚拟号', trigger: 'change' }
      ],
      callDuration: [
        { required: true, message: '请输入通话时长', trigger: 'blur' }
      ],
      totalFee: [
        { required: true, message: '请输入总费用', trigger: 'blur' }
      ],
      virtualFee: [
        { required: true, message: '请输入服务费', trigger: 'blur' }
      ]
    }
    
    // 获取去重后的主叫手机号列表
    const uniqueCallerPhones = computed(() => {
      if (!allVirtualNumbers.value || allVirtualNumbers.value.length === 0) {
        return []
      }
      const phoneSet = new Set(allVirtualNumbers.value.map(virtual => virtual.ownerPhone))
      return Array.from(phoneSet)
    })
    
    // 根据主叫手机号过滤虚拟号列表
    const filteredVirtualNumbers = computed(() => {
      if (!form.callerPhone) {
        return []
      }
      return allVirtualNumbers.value.filter(virtual => virtual.ownerPhone === form.callerPhone)
    })
    
    // 获取手机号标签显示文本
    const getPhoneLabel = (phone) => {
      const phoneText = phone.phone || '';
      // 可以根据需要添加客户信息
      return phoneText;
    }
    
    // 获取虚拟号列表（包含绑定的手机号）
    const fetchVirtualNumbers = async () => {
      try {
        const res = await getVirtualNumberInfo()
        if (res.code === 0) {
          // 处理不同类型的响应数据结构
          if (Array.isArray(res.data)) {
            allVirtualNumbers.value = res.data
          } else if (res.data && Array.isArray(res.data.records)) {
            allVirtualNumbers.value = res.data.records
          } else {
            allVirtualNumbers.value = []
          }
        } else {
          allVirtualNumbers.value = []
        }
      } catch (error) {
        console.error('获取虚拟号列表失败:', error)
        ElMessage.error('获取虚拟号列表失败')
        allVirtualNumbers.value = []
      }
    }
    
    // 获取被叫手机号列表
    const fetchCalleePhoneNumbers = async () => {
      try {
        const res = await getPhoneNumberInfo()
        if (res.code === 0) {
          // 处理不同类型的响应数据结构
          if (Array.isArray(res.data)) {
            calleePhoneNumbers.value = res.data
          } else if (res.data && Array.isArray(res.data.records)) {
            calleePhoneNumbers.value = res.data.records
          } else {
            calleePhoneNumbers.value = []
          }
        } else {
          calleePhoneNumbers.value = []
        }
      } catch (error) {
        console.error('获取被叫手机号列表失败:', error)
        ElMessage.error('获取被叫手机号列表失败')
        calleePhoneNumbers.value = []
      }
    }
    
    // 获取账单详情
    const fetchBillDetail = async (id) => {
      if (!id) return;
      
      try {
        const res = await getBillInfoById(id)
        if (res.code === 0 && res.data) {
          const data = res.data
          form.id = data.id
          form.callerPhone = data.callerPhone
          form.calleePhone = data.calleePhone
          form.virtualNumber = data.virtualNumber
          form.callDuration = data.callDuration
          // 将分转换为元显示
          form.totalFee = data.totalFee ? (data.totalFee / 100) : 0
          form.virtualFee = data.virtualFee ? (data.virtualFee / 100) : 0
        } else {
          ElMessage.error(res?.msg || '获取账单详情失败')
        }
      } catch (error) {
        console.error('获取账单详情失败:', error)
        ElMessage.error('获取账单详情失败')
      }
    }
    
    // 当主叫手机号改变时，清空已选择的虚拟号
    const handleCallerPhoneChange = (callerPhone) => {
      form.virtualNumber = ''
    }
    
    // 重置表单
    const resetForm = () => {
      Object.keys(form).forEach(key => {
        if (key === 'id') {
          form[key] = ''
        } else if (key === 'callDuration' || key === 'totalFee' || key === 'virtualFee') {
          form[key] = 0
        } else {
          form[key] = ''
        }
      })
    }
    
    // 关闭弹窗
    const handleClose = () => {
      resetForm()
      emit('update:visible', false)
    }
    
    // 提交表单
    const handleSubmit = async () => {
      try {
        await formRef.value.validate()
        submitLoading.value = true
        
        // 准备请求数据（将元转换为分）
        const requestData = {
          id: form.id,
          callerPhone: form.callerPhone,
          calleePhone: form.calleePhone,
          virtualNumber: form.virtualNumber,
          callDuration: form.callDuration,
          totalFee: Math.round(form.totalFee * 100),
          virtualFee: Math.round(form.virtualFee * 100)
        }
        
        const res = await updateBillInfo(requestData)
        if (res.code === 0) {
          ElMessage.success('账单修改成功')
          resetForm()
          emit('success')
          handleClose()
        } else {
          ElMessage.error(res.msg || '修改失败')
        }
      } catch (error) {
        console.error('修改账单失败:', error)
        ElMessage.error('修改账单失败')
      } finally {
        submitLoading.value = false
      }
    }
    
    // 监听账单ID变化，获取账单详情
    watch(
      () => props.billId,
      (newId) => {
        if (newId) {
          fetchBillDetail(newId)
        }
      },
      { immediate: true }
    )
    
    // 初始化获取数据
    onMounted(() => {
      fetchVirtualNumbers()
      fetchCalleePhoneNumbers()
    })
    
    // 暴露方法给父组件
    return {
      formRef,
      form,
      rules,
      submitLoading,
      allVirtualNumbers,
      calleePhoneNumbers,
      uniqueCallerPhones,
      filteredVirtualNumbers,
      getPhoneLabel,
      resetForm,
      handleClose,
      handleSubmit,
      handleCallerPhoneChange
    }
  }
}
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>